import { Player } from "../player";
import { Vector2 } from "../vector";
import { Engine } from "../engine";
import { assets } from "../assets";

// src/projectiles/projectile-manager.ts  
interface Projectile {
    pos: Vector2;
    vel: Vector2;
    startTime: number;
    lifetime: number;
    damage: number;
    isActive: boolean;
    // 新增爆炸动画相关属性  
    isExploding: boolean;
    explosionStartTime: number;
    explosionFrame: number;
}

interface SpriteFrame {
    x: number;      // 帧在精灵表中的X坐标  
    y: number;      // 帧在精灵表中的Y坐标  
    width: number;  // 帧的宽度  
    height: number; // 帧的高度  
}

/**
 * 投射物管理器类，负责创建、更新和渲染游戏中的投射物
 * 
 * 功能包括：
 * - 创建新的投射物并设置初始属性（位置、方向、速度等）
 * - 每帧更新所有活跃投射物的状态（位置、生命周期、碰撞检测）
 * - 处理投射物与游戏世界的碰撞检测和响应
 * - 渲染所有活跃的投射物到画布上
 * 
 * 投射物具有以下特性：
 * - 固定生命周期（默认3秒）
 * - 碰撞后会产生粒子效果并消失
 * - 带有发光效果的蓝色圆形外观
 */
export class ProjectileManager {
    private projectiles: Projectile[] = [];
    private frameDuration = 50; // 每帧持续时间(毫秒)  

    private explosionFrames: SpriteFrame[] = [
        { x: 0, y: 0, width: 419, height: 415 }, // 第1帧
        { x: 421, y: 0, width: 424, height: 413 }, // 第2帧
        { x: 1, y: 416, width: 410, height: 364 }, // 第3帧
        { x: 414, y: 417, width: 415, height: 360 }, // 第4帧
        // { x: 0, y: 782, width: 401, height: 388 }, // 第5帧
        // { x: 402, y: 781, width: 410, height: 392 }, // 第6帧
        // { x: 8, y: 1180, width: 363, height: 361 }, // 第7帧
        // { x: 387, y: 1174, width: 337, height: 330 }, // 第8帧
        // { x: 8, y: 1547, width: 361, height: 375 }, // 第9帧
        // { x: 376, y: 1524, width: 330, height: 340 }, // 第10帧
    ];


    createProjectile(startPos: Vector2, direction: Vector2, speed: number) {
        const projectile: Projectile = {
            pos: startPos.copy(),
            vel: direction.normalize_().mul(speed),
            startTime: Date.now(),
            lifetime: 1000 * 60, // 3秒生命周期  
            damage: 50,
            isActive: true,
            isExploding: false,
            explosionStartTime: 0,
            explosionFrame: 0
        };
        this.projectiles.push(projectile);
    }

    update(engine: Engine) {
        for (let i = this.projectiles.length - 1; i >= 0; i--) {
            const projectile = this.projectiles[i];

            if (!projectile.isActive || Date.now() - projectile.startTime > projectile.lifetime) {
                this.projectiles.splice(i, 1);
                continue;
            }

            // 更新位置  
            projectile.pos.add_(projectile.vel);

            // 检查碰撞  
            this.checkProjectileCollisions(projectile, engine);
        }
    }

    private checkProjectileCollisions(projectile: Projectile, engine: Engine) {
        // 利用现有的物理系统检查碰撞  
        const collisions = Array.from(engine.physics.checkHitterColisions({
            radius: 5,
            pos: projectile.pos,
            oldPos: projectile.pos.copy(),
            vel: projectile.vel,
            contactPoints: []
        }));
        // console.log("checkProjectileCollisions", collisions);

        if (!projectile.isExploding && collisions.length > 0) {
            // 碰撞时产生爆炸效果  
            //   engine.particles.emit({  
            //     count: 20,  
            //     direction_: new Vector2(3, 0),  
            //     lifetime: 100,  
            //     pos: projectile.pos,  
            //   }); 

            // 开始爆炸动画  
            projectile.isExploding = true;
            projectile.explosionStartTime = Date.now();
            projectile.vel.zero(); // 停止移动  
        }
    }

    private renderExplosion(ctx: CanvasRenderingContext2D, projectile: Projectile) {
        if (!projectile.isExploding) return;

        const elapsed = Date.now() - projectile.explosionStartTime;
        const currentFrameIndex = Math.floor(elapsed / this.frameDuration);

        console.log("renderExplosion elapsed", elapsed);
        console.log("renderExplosion currentFrameIndex", currentFrameIndex);

        if (currentFrameIndex >= this.explosionFrames.length) {
            projectile.isActive = false;
            projectile.isExploding = false;
            return;
        }

        const frame = this.explosionFrames[currentFrameIndex];
        const scale = 0.2; // 统一缩放比例  

        ctx.save();
        ctx.translate(projectile.pos.x, projectile.pos.y);

        ctx.drawImage(
            assets.explosion001,
            frame.x, frame.y,
            frame.width, frame.height,
            -frame.width * scale / 2, -frame.height * scale / 2,
            frame.width * scale, frame.height * scale
        );

        ctx.restore();
    }

    render(ctx: CanvasRenderingContext2D) {
        for (const projectile of this.projectiles) {
            if (projectile.isExploding) {
                this.renderExplosion(ctx, projectile);
            } else if (projectile.isActive) {

                ctx.save();
                ctx.translate(projectile.pos.x, projectile.pos.y);

                // // 绘制魔法弹  
                // ctx.fillStyle = "#00f";  
                // ctx.beginPath();  
                // ctx.arc(0, 0, 5, 0, Math.PI * 2);  
                // ctx.fill();  

                // 使用PNG图片替代简单圆形  
                ctx.drawImage(assets.magicProjectile, -10, -10, 20, 20);

                // 添加发光效果  
                ctx.shadowColor = "#00f";
                ctx.shadowBlur = 10;
                ctx.fill();

                ctx.restore();
            }
        }
    }
}